package com.zyfu.demo.concurrent.future;

import org.junit.jupiter.api.Test;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * <b>请输入名称</b>
 * <pre>
 * 描述<br/>
 * 作用：；<br/>
 * 限制：；<br/>
 * </pre>
 *
 * @author 张永福
 * @since 2024/3/19 17:27
 */
public class FutureDemo {

    @Test
    public void future1() {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Future<String> future = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(3000);
                return "hello";
            }
        });

        try {
            String s = future.get();
            System.out.println(s);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        executorService.shutdown();
    }

    @Test
    public void future2() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);

        System.out.println("开始时间---" + LocalTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")));
        /*
         * 延迟执行方法，在指定时间段之后执行一次，注意：如果还没有到达执行的时间点，线程池shutdown, 则任务不会被触发
         */
        ScheduledFuture<String> schedule = scheduledExecutorService.schedule(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("--------延迟执行:" + LocalTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")));
                return null;
            }
        }, 3, TimeUnit.SECONDS);

        /*
         * 周期执行方法会立即执行一次，然后再进行周期执行
         */
        ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("定时执行:" + LocalTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")));
            }
        }, 0, 1, TimeUnit.SECONDS);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            scheduledExecutorService.shutdown();
        }
    }
}
